﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HomeWork
{
    internal class Captcha
    {
        // 定义用于生成验证码的字符集，移除了容易混淆的 0, o, O, 1, i, I, l, L 等字符
        private static readonly string CharPool = "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz";

        /// <summary>
        /// 自定义验证码生成异常
        /// </summary>
        public class CaptchaGenerationException : Exception
        {
            public CaptchaGenerationException(string message) : base(message) { }
            public CaptchaGenerationException(string message, Exception innerException)
                : base(message, innerException) { }
        }

        /// <summary>
        /// 生成指定长度的随机字符串
        /// </summary>
        /// <param name="length">验证码长度</param>
        /// <returns>随机字符串</returns>
        internal  string GenerateRandomCode(int length)
        {
            //Random rand = new Random();
            //char[] code = new char[length];

            //for (int i = 0; i < length; i++)
            //{
            //    code[i] = CharPool[rand.Next(CharPool.Length)];
            //}
            //return new string(code);

            if (length <= 0)
                throw new CaptchaGenerationException("验证码长度必须大于0");

            try
            {
                Random rand = new Random();
                char[] code = new char[length];

                for (int i = 0; i < length; i++)
                {
                    code[i] = CharPool[rand.Next(CharPool.Length)];
                }
                return new string(code);
            }
            catch (Exception ex)
            {
                throw new CaptchaGenerationException("生成验证码文本时出错", ex);
            }
        }

        /// <summary>
        /// 将文本绘制成验证码图片
        /// </summary>
        /// <param name="code">验证码文本</param>
        /// <returns>图片的字节数组</returns>
        //internal static byte[] CreateCaptchaImage(string code)
        //{
        //    // 定义图片尺寸（宽度随文本长度自适应）
        //    int width = code.Length * 25;
        //    int height = 40;

        //    // 创建位图并获取绘图表面
        //    using (Bitmap bitmap = new Bitmap(width, height)) 
        //    using (Graphics graphics = Graphics.FromImage(bitmap))
        //    {
        //        graphics.Clear(Color.White); // 设置白色背景

        //        Random rand = new Random();

        //        // 添加几条干扰线，增加识别难度
        //        for (int i = 0; i < 5; i++)
        //        {
        //            Pen pen = new Pen(Color.Silver, 1);
        //            graphics.DrawLine(pen,
        //                rand.Next(width), rand.Next(height),
        //                rand.Next(width), rand.Next(height));
        //        }

        //        // 设置字体并绘制验证码文本
        //        Font font = new Font("Arial", 16, FontStyle.Bold);
        //        // 使用渐变画刷让文字颜色有所变化
        //        using (LinearGradientBrush brush = new LinearGradientBrush(
        //            new Rectangle(0, 0, width, height),
        //            Color.Blue, Color.DarkRed, 1.2f, true))
        //        {
        //            graphics.DrawString(code, font, brush, 10, 8);
        //        }

        //        // 将图片保存到内存流，并返回字节数组
        //        using (MemoryStream ms = new MemoryStream())
        //        {
        //            bitmap.Save(ms, ImageFormat.Jpeg);
        //            return ms.ToArray();
        //        }
        //    }
        //}

        /// <summary>
        /// 将文本绘制成验证码图片
        /// </summary>
        /// <param name="code">验证码文本</param>
        /// <param name="width">图片宽度（可选）</param>
        /// <param name="height">图片高度（可选）</param>
        /// <returns>图片的字节数组</returns>
        public byte[] CreateCaptchaImage(string code, int width = 0, int height = 40)
        {
            if (string.IsNullOrWhiteSpace(code))
                throw new CaptchaGenerationException("验证码文本不能为空");

            try
            {
                // 如果未指定宽度，则根据文本长度自适应
                if (width <= 0)
                    width = code.Length * 25;

                if (height <= 0)
                    throw new CaptchaGenerationException("图片高度必须大于0");

                using (Bitmap bitmap = new Bitmap(width, height))
                using (Graphics graphics = Graphics.FromImage(bitmap))
                {
                    graphics.Clear(Color.White); // 设置白色背景

                    Random rand = new Random();

                    // 添加干扰线
                    for (int i = 0; i < 5; i++)
                    {
                        using (Pen pen = new Pen(Color.Silver, 1))
                        {
                            graphics.DrawLine(pen,
                                rand.Next(width), rand.Next(height),
                                rand.Next(width), rand.Next(height));
                        }
                    }

                    // 设置字体并绘制验证码文本
                    using (Font font = new Font("Arial", 16, FontStyle.Bold))
                    using (LinearGradientBrush brush = new LinearGradientBrush(
                        new Rectangle(0, 0, width, height),
                        Color.Blue, Color.DarkRed, 1.2f, true))
                    {
                        graphics.DrawString(code, font, brush, 10, 8);
                    }

                    // 将图片保存到内存流
                    using (MemoryStream ms = new MemoryStream())
                    {
                        bitmap.Save(ms, ImageFormat.Jpeg);
                        return ms.ToArray();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new CaptchaGenerationException("生成验证码图片时出错", ex);
            }
        }

        /// <summary>
        /// 将验证码图片保存到文件
        /// </summary>
        /// <param name="imageBytes">图片字节数组</param>
        /// <param name="filePath">文件路径</param>
        public void SaveCaptchaImage(byte[] imageBytes, string filePath)
        {
            if (imageBytes == null || imageBytes.Length == 0)
                throw new CaptchaGenerationException("图片数据为空");

            if (string.IsNullOrWhiteSpace(filePath))
                throw new CaptchaGenerationException("文件路径不能为空");

            try
            {
                File.WriteAllBytes(filePath, imageBytes);
            }
            catch (Exception ex)
            {
                LogException(ex);
                throw new CaptchaGenerationException("保存验证码图片时出错", ex);
            }
        }

        /// <summary>
        /// 记录异常到日志文件
        /// </summary>
        /// <param name="ex">异常对象</param>
        private void LogException(Exception ex)
        {
            string logPath = @"F:\17bang\captcha_errors.log";
            try
            {
                using (StreamWriter writer = new StreamWriter(logPath, true))
                {
                    writer.WriteLine($"[{DateTime.Now}] 异常信息: {ex.Message}");
                    writer.WriteLine($"异常类型: {ex.GetType().FullName}");
                    writer.WriteLine($"堆栈跟踪: {ex.StackTrace}");
                    writer.WriteLine(new string('-', 80));

                    if (ex.InnerException != null)
                    {
                        writer.WriteLine($"内部异常: {ex.InnerException.Message}");
                        writer.WriteLine($"内部异常类型: {ex.InnerException.GetType().FullName}");
                        writer.WriteLine($"内部异常堆栈: {ex.InnerException.StackTrace}");
                    }
                }
            }
            catch
            {
                // 日志记录失败时不做处理，避免无限递归
            }
        }
    }
}
